package server

import (
	"coolcar/shared/auth"
	"net"

	"go.uber.org/zap"
	"google.golang.org/grpc"
)

//GRPCConfig define a grpc server
type GRPCConfig struct {
	Name              string
	Addr              string
	AuthPublicKeyFile string
	Logger            *zap.Logger
	RegisterFunc      func(server *grpc.Server)
}

//RunGRPCServer runs a grpc server
func RunGRPCServer(c *GRPCConfig) error {
	logger := c.Logger
	fieldName := zap.String("name", c.Name)
	listen, err := net.Listen("tcp", c.Addr)
	if err != nil {
		logger.Fatal("can not listen", fieldName, zap.Error(err))
	}
	var opts []grpc.ServerOption
	if c.AuthPublicKeyFile != "" {
		in, err := auth.Interceptor(c.AuthPublicKeyFile)
		if err != nil {
			logger.Fatal("can not get interceptor", zap.Error(err))
		}
		opts = append(opts, grpc.UnaryInterceptor(in))
	}
	server := grpc.NewServer(opts...)
	c.RegisterFunc(server)
	return server.Serve(listen)
}
